package com.xzq.bustack.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 12:17
 * @Version 1.0.0
 **/
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(MyServerHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel sc = (SocketChannel) ctx.channel();
        logger.info("连接建立....");
        logger.info("客户端连接到本地服务器");
        logger.info("连接IP：" + sc.localAddress().getHostString());
        logger.info("连接端口：" + sc.localAddress().getPort());
        logger.info("连接报告完毕");

        //通知客户端连接建立成功
        String str = "连接建立成功： I am SpringBoot Server";
        ctx.writeAndFlush(str);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.error("客户端断开连接{}", ctx.channel().localAddress().toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        logger.info("连接异常： {}", cause.getMessage());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("服务端收到消息：" + msg);
        //通知客户端成功接受消息
        String str = "收到信息!";
        ctx.writeAndFlush(msg);
    }
}
